import numpy as np
import cv2
from conf import *

def set_camera(width, height):
    cap = cv2.VideoCapture(0)  # 打开摄像头 最大范围 640×480
    cap.set(3, width)  # 设置画面宽度
    cap.set(4, height)  # 设置画面高度
    return cap


def ocilid(x, y):
    return np.sqrt(np.sum((y - x) ** 2))


def count_angle(x, y):
    return x * y / np.sqrt(np.sum(x ** 2) * np.sum(y ** 2))


# def is_rect(cnt):
#     v = np.array([cnt[1] - cnt[0], cnt[2] - cnt[1], cnt[3] - cnt[2], cnt[0] - cnt[3]])
#     a = np.array([count_angle(v[0], v[1]), count_angle(v[1], v[2]), count_angle(v[2], v[3]), count_angle(v[3], v[0])])
#     if 1.04 < np.arccos(a.all()) < 2.09:
#         return True
#     return False

def is_square(cnt):
    counter = cnt.squeeze()
    l1, l2, l3, l4 = ocilid(counter[0], counter[1]), ocilid(counter[1], counter[2]), ocilid(counter[2],
                                                                                            counter[3]), ocilid(
        counter[3], counter[0])
    # if max(l1, l2, l3, l4) / min(l1, l2, l3, l4) < 1.5 and min(l1, l2, l3, l4) > 20 and is_rect(counter):
    if max(l1, l2, l3, l4) / min(l1, l2, l3, l4) < 1.5 and min(l1, l2, l3, l4) > 20:
        return True
    return False


def set_color(color):
    if color == 'blue':
        return blue_lower, blue_upper
    elif color == 'red':
        return red_lower1, red_upper1, red_lower2, red_upper2
    elif color == 'green':
        return green_lower, green_upper
    elif color == 'yellow':
        return yellow_lower, yellow_upper
